package com.zhenai;

import static org.jredis.ri.alphazero.support.DefaultCodec.toStr;

import java.util.ArrayList;
import java.util.List;

import org.jredis.JRedis;
import org.jredis.KeyValueSet;
import org.jredis.RedisException;
import org.jredis.ri.alphazero.BulkSetMapping;
import org.jredis.ri.alphazero.JRedisClient;
import org.jredis.ri.alphazero.support.DefaultCodec;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.zhenai.bean.Classes;
import com.zhenai.bean.User;



public class TestAdd {

	private JRedis jredis = null;
	private static final String host = "10.10.121.200";
	private static final int port = 6379;//JRedis默认的端口来监听客户端的请求
	private static final String key = "test-jredis";
	private KeyValueSet kvSet = BulkSetMapping.newByteArrayKVSet();
	
	private long start = 0l;
	private long end = 0l;
	
	@Before
	public void setUp(){
		start = System.currentTimeMillis();
		jredis = new JRedisClient(host, port,"jredis",0);
	}
	
	@Test
	public void testConnection(){
		try {
			jredis.ping();
			if(!jredis.exists(key)) {
				jredis.set(key, "Hello World");
				System.out.format("Hello!  You should run me again!\n");
			}
			else {
				String msg = toStr ( jredis.get(key) );
				System.out.format("%s\n", msg);
			}
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testAddObject(){
		
		for (int i = 1; i < 1000; i++) {
			Classes c = new Classes("一班", i);
			User user = new User("小王" + i, i);
			user.setClasses(c);
			// get the next available object id from our Redis counter using INCR command
			long id = 0l;
			try {
				id = jredis.incr("User::next_id");
			} catch (RedisException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// we can bind it a unique key using map (Redis "String") semantics now
			String key = "objects::User::" + id;
			//kvSet.add(key, user);
			// voila: java object db
			try {
				jredis.set(key, user);
				jredis.sadd("users", user);
			} catch (RedisException e) {
				e.printStackTrace();
			}
			// and lets add it to this set too since this is so much fun
			
		}
		

		List<User> members = new ArrayList<User>();
		try {
			members = DefaultCodec.decode(jredis.smembers("users"));
		} catch (RedisException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (User user : members) {
			System.out.println("id:" + user.getId());
			System.out.println("name:" + user.getName());
			System.out.println("class:"+user.getClasses().getName());
		}

		System.out.format(" and done.\n");
	}
	@After
	public void tearDown(){
		end = System.currentTimeMillis();
		jredis.quit();
		System.out.println("total cost time:"+(end-start)+"ms");
	}
}
